package org.qiyu.live.id.generate.provider.service.impl;

import jakarta.annotation.Resource;
import org.qiyu.live.id.generate.provider.dao.mapper.IdGenerateMapper;
import org.qiyu.live.id.generate.provider.dao.po.IdGeneratePO;
import org.qiyu.live.id.generate.provider.service.IdGenerateService;
import org.qiyu.live.id.generate.provider.service.bo.LocalSeqIdBO;
import org.qiyu.live.id.generate.provider.service.bo.LocalUnSeqIdBO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;



@Service
public class
IdGenerateServiceImpl implements IdGenerateService, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(IdGenerateServiceImpl.class);

    private static Map<Integer, LocalSeqIdBO> localSeqIdBOMap =new ConcurrentHashMap<>();
    private static Map<Integer, LocalUnSeqIdBO> localUnSeqIdBOMap =new ConcurrentHashMap<>();

    private static Map<Integer,Semaphore> semaphoreMap =new ConcurrentHashMap<>();
    private static final  float UPDATE_RATE=0.75f;

    @Resource
    private IdGenerateMapper idGenerateMapper;

    private static final ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(8, 16, 3, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("id-generate-thread-"+ThreadLocalRandom.current().nextInt(1000));
            return thread;
        }
    });



    @Override
    public Long getSeqId(Integer id) {
        //判断参数是否合法
        if(id == null){
            LOGGER.error("getSeqId is error,id is {}",id);
            return null;
        }
        LocalSeqIdBO localSeqIdBO = localSeqIdBOMap.get(id);
        if(localSeqIdBO == null ){
            LOGGER.error("getSeqId is error,id is {}",id);
            return null;
        }
        //当map中的值用到75%的时候进行更新
        this.refreshLocalSeqId(localSeqIdBO);
        //getAndIncrement这个方法就是拿到currentNum并自增1
        long returnId = localSeqIdBO.getCurrentNum().getAndIncrement();

        if(returnId>localSeqIdBO.getNextThreshold()){
            LOGGER.error("[getSeqId] id is over limit,id is {}",id);
            return null;
        }

        return returnId;
    }

    @Override
    public Long getUnSeqId(Integer id) {
        if(id == null){
            LOGGER.error("getUnSeqId is error,id is {}",id);
            return null;
        }
        LocalUnSeqIdBO localUnSeqIdBO = localUnSeqIdBOMap.get(id);
        if(localUnSeqIdBO==null){
            LOGGER.error("getUnSeqId is error,id is {}",id);
            return null;
        }

        //当map中的值用到75%的时候进行更新
        this.refreshLocalUnSeqId(localUnSeqIdBO);
        Long returnId = localUnSeqIdBO.getIdQueue().poll();
        if(returnId>localUnSeqIdBO.getNextThreshold()){
            LOGGER.error("[getUnSeqId] id is over limit,id is {}",id);
            return null;
        }

        return returnId;
    }

    private void refreshLocalUnSeqId(LocalUnSeqIdBO localUnSeqIdBO) {
        Long begin = localUnSeqIdBO.getCurrentStart();
        Long end = localUnSeqIdBO.getNextThreshold();
        int remainSize = localUnSeqIdBO.getIdQueue().size();

        if((end - begin)* 0.25 > remainSize){
            Semaphore semaphore = semaphoreMap.get(localUnSeqIdBO.getId());
            if(semaphore == null){
                LOGGER.error("semaphore is null,id is {}",localUnSeqIdBO.getId());
            }
            boolean tryAcquire = semaphore.tryAcquire();
            if(tryAcquire){
                LOGGER.info("尝试进行id同步");
                threadPoolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            IdGeneratePO idGeneratePO = idGenerateMapper.selectById(localUnSeqIdBO.getId());
                            tryUpdateMySQLRecord(idGeneratePO);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        } finally {
                            //释放信号量
                            semaphoreMap.get(localUnSeqIdBO.getId()).release();
                        }
                    }
                });

            }

        }

    }


    /**
     * 当map中的值用到75%的时候进行更新
     * @param localSeqIdBO
     */
    private void refreshLocalSeqId(LocalSeqIdBO localSeqIdBO) {
        Long currentStart = localSeqIdBO.getCurrentStart();
        Long nextThreshold = localSeqIdBO.getNextThreshold();
        Long step = nextThreshold-currentStart;

        if(localSeqIdBO.getCurrentNum().get()-localSeqIdBO.getCurrentStart()>step*UPDATE_RATE){
            //只允许一个线程去进行更新操作
            Semaphore semaphore = semaphoreMap.get(localSeqIdBO.getId());
            if(semaphore==null){
                LOGGER.error("semaphore is null,id is {}",localSeqIdBO.getId());
            }
            boolean tryAcquire = semaphore.tryAcquire();
            if(tryAcquire){
                LOGGER.info("尝试进行id同步");
                threadPoolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            IdGeneratePO idGeneratePO = idGenerateMapper.selectById(localSeqIdBO.getId());
                            tryUpdateMySQLRecord(idGeneratePO);
                        } catch (Exception e) {
                            LOGGER.error("[refreshLocalSeqId] error is ",e);
                            throw new RuntimeException(e);
                        } finally {
                            //释放信号量
                            semaphoreMap.get(localSeqIdBO.getId()).release();
                            LOGGER.info("本地有序id段同步完成，id is {} ",localSeqIdBO.getId());
                        }
                    }
                });
            }
        }
    }



    private void tryUpdateMySQLRecord(IdGeneratePO idGeneratePO) {
        Integer updateResult = idGenerateMapper.updateNewIdCountAndVersion(idGeneratePO.getId(),idGeneratePO.getVersion());
        if(updateResult>0){
            //如果有序，则放到localSeqIdBOMap
            localIdHandler(idGeneratePO);
            return;
        }
        for (int i = 0; i < 3; i++) {
            idGeneratePO = idGenerateMapper.selectById(idGeneratePO.getId());
            updateResult =idGenerateMapper.updateNewIdCountAndVersion(idGeneratePO.getId(),idGeneratePO.getVersion());
            if(updateResult>0){
                localIdHandler(idGeneratePO);
                return;
            }
        }
        throw new RuntimeException("表id段占用失败，竞争过于激烈，id is {}"+idGeneratePO.getId());

    }


    @Override
    public void afterPropertiesSet() throws Exception {
        List<IdGeneratePO> idGeneratePOS = idGenerateMapper.selectAll();
        for (IdGeneratePO idGeneratePO : idGeneratePOS) {
            tryUpdateMySQLRecord(idGeneratePO);
            semaphoreMap.put(idGeneratePO.getId(),new Semaphore(1));
        }
    }


    private void localIdHandler(IdGeneratePO idGeneratePO){
        if(idGeneratePO.getIsSeq()==1){
            int id = idGeneratePO.getId();
            long currentStart = idGeneratePO.getCurrentStart();
            long nextThreshold = idGeneratePO.getNextThreshold();
            Long currentNum = currentStart;
            AtomicLong atomicLong = new AtomicLong(currentNum);
            LocalSeqIdBO localSeqIdBO = new LocalSeqIdBO();
            localSeqIdBO.setCurrentStart(currentStart);
            localSeqIdBO.setNextThreshold(nextThreshold);
            localSeqIdBO.setId(id);
            localSeqIdBO.setCurrentNum(atomicLong);
            localSeqIdBOMap.put(id,localSeqIdBO);
        }else {
            long start = idGeneratePO.getCurrentStart();
            long end = idGeneratePO.getNextThreshold();
            ArrayList<Long> idList = new ArrayList<>();
            for (long i = start; i < end; i++) {
                idList.add(i);
            }
            //打乱集合中的数据
            Collections.shuffle(idList);
            ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<>();
            queue.addAll(idList);
            LocalUnSeqIdBO localUnSeqIdBO = new LocalUnSeqIdBO();
            localUnSeqIdBO.setIdQueue(queue);
            localUnSeqIdBO.setCurrentStart(start);
            localUnSeqIdBO.setNextThreshold(end);
            localUnSeqIdBO.setId(idGeneratePO.getId());
            localUnSeqIdBOMap.put(idGeneratePO.getId(),localUnSeqIdBO);
        }
    }




}
